import matplotlib.pyplot as plt
import numpy as np


def draw(maps, chart_type='bar', x_label='group', y_label='proportion', title='data distribution', legend=True, save=None):
    """
    maps: {
        'series_A': {'x': [], 'y': []},
        'series_B': {'x': [], 'y': []}
    }
    """
    total_width, n = 0.8, len(maps)
    single_width = total_width / n
    pos = np.arange(len(maps[list(maps.keys())[0]]['x']))  # - (total_width - single_width) / 2
    plt.rcParams['axes.unicode_minus'] = False
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    plt.title(title)
    plt.grid(color='#95a5a6', linestyle='--', linewidth=1, axis='y', alpha=0.4)
    index = 0
    if chart_type == 'bar':
        for key in maps:
            value = maps[key]
            plt.bar(pos + index * single_width, value['y'], width=single_width, label=key)
            index = index + 1
        plt.xticks(pos + (index - 1) * single_width / 2, maps[list(maps.keys())[0]]['x'])
    elif chart_type == 'line':
        for key in maps:
            value = maps[key]
            plt.plot(value['x'], value['y'], label=key)
    if legend:
        plt.legend()
    if save is not None:
        plt.savefig(save, format='svg')
    plt.show()


def draw_double(maps1, maps2, title=''):
    series1 = list(maps1.keys())[0]
    series2 = list(maps2.keys())[0]
    fig = plt.figure()
    fig.suptitle(title)
    ax1 = fig.add_subplot(111)
    ax1.plot(maps1[series1]['x'], maps1[series1]['y'], 'r', label=series1)
    ax1.legend(loc=1)
    ax1.set_ylabel(series1)
    ax2 = ax1.twinx()
    ax2.plot(maps2[series2]['x'], maps2[series2]['y'], 'g', label=series2)
    ax2.legend(loc=2)
    ax2.set_ylabel(series2)
    plt.show()


if __name__ == '__main__':
    # draw({'200w': {'x': [1, 2, 3], 'y': [3, 4, 5]}})
    # draw({'lineitem_inc_200w': {'x': [0, 500], 'y': [9929, 10855]}})
    draw_double({'100w': {'x': [100, 200, 300], 'y': [3, 4, 5]}},
                {'200w': {'x': [100, 200, 300], 'y': [5, 3, 4]}})
